<?php

namespace app\merchants\model;

use app\common\loader\ModelMerchant;
use app\common\model\shop\ShopStockModel;
use think\db\exception\DbException;
use think\Exception;
use think\facade\Db;

/**
 * 店铺商品库存信息
 * Class ShopStock
 * @package app\common\model\shop
 */
class ShopStock extends ShopStockModel
{

    /**
     * 预警状态修改
     * @param $id
     * @param $type
     * @return int
     * @throws DbException
     */
    public function shopSaveWarn($id, $type): int
    {
        return $this->db()->where('id', $id)->update(['warn_flag' => $type]);
    }


    /**
     * 更新添加
     * @param $productData | 更新数据
     * @param $shop_id |店铺
     * @throws DbException
     */
    public function shopSave($productData, string $merId, int $shop_id)
    {
        //店铺库存数据
        $shop_data = $this->db()->where('shop_id', $shop_id)
            ->column('id,in_num,sum_num,product_code', 'product_code');
        $now = date('Y-m-d H:i:s');
        $insertData = $updateData = [];
        foreach ($productData as $v) {
            if (isset($shop_data[$v['product_code']])) {
                $s =& $shop_data[$v['product_code']];
                $updateData[$s['id']] = $v['num'];
            } else {
                $insertData[] = [
                    'mer_id' => $merId,
                    'shop_id' => $shop_id,
                    'product_code' => $v['product_code'],
                    'in_num' => $v['num'],
                    'sum_num' => $v['num'],
                    'update_ad' => $now,
                ];
            }
        }
        if (!empty($insertData)) {
            $this->db()->insertAll($insertData);
        }
        $db = $this->db();
        foreach ($updateData as $id => $num) {
            $db->removeOption()->where('id', $id)->update([
                'in_num' => Db::raw('in_num+' . $num),
                'sum_num' => Db::raw('sum_num+' . $num),
                'update_at' => $now
            ]);
        }
        return;
    }


    /**
     * 库存详情
     * @param $id
     */
    public function shopInfo($id)
    {
        //门店， 商品名称， 分类， 库存数量
        //return $this->db()->where('id', $id)->find();
        return $this->db()->alias('a')
            ->join('product b', 'a.product_code=b.code', 'left')
            ->where('a.id', $id)
            ->where('a.mer_id=b.mer_id')
            ->field('a.id,product_code,shop_id,a.mer_id,out_num,in_num,sum_num,warn_flag,a.update_at,b.title as product_tag,b.class_id,b.sub_title')
            ->find();
    }

    /**
     * 分页
     * @param  $where
     * @param  $page
     * @param  $count
     * @return mixed
     * @throws DbException
     */
    public function shopStockPage($where, $page = 1, $count = 30)
    {

        return $this->db()->where($where)
            ->group("shop_id")
            ->order('shop_id desc')
            ->field('shop_id,SUM(in_num) as in_num,SUM(out_num) as out_num,SUM(sum_num) as sum_num')
            ->paginate(['page' => $page, 'list_rows' => $count]);

    }



    /**
     * 分页
     * @param  $where
     * @param  $page
     * @param  $count
     * @return mixed
     * @throws DbException
     */
    public function shopPage($where, $page = 1, $count = 30)
    {

        return $this->db()->alias('a')
            ->join('product b', 'a.product_code=b.code', 'left')
            ->where($where['where'])
            ->where($where['where_num'])
            ->where('a.mer_id=b.mer_id')
            ->whereNull('b.delete_at')
            ->order('a.shop_id desc')
            ->field('a.id,product_code,shop_id,a.mer_id,out_num,in_num,sum_num,warn_flag,a.update_at,b.title as product_tag,
            b.class_id,b.sub_title,b.warn_num')
            ->paginate(['page' => $page, 'list_rows' => $count]);
    }

    /**
     * 预警数据
     * @param $mer_id | 库存数
     * @return int
     */
    public function getStockDeficiency($mer_id,$shop_id): int
    {
        $where[] = ['s.mer_id' , '=' , $mer_id];
        if (!empty($shop_id)){
            $where[] = ['s.shop_id' , '=' , $shop_id];
        }
        return  $this->db()->alias('s')
            ->join('product b', 's.product_code=b.code', 'left')
            ->where('s.mer_id=b.mer_id')->where('b.warn_num' , '<>' , 0)
            ->where(['s.warn_flag' => 1])
            ->where($where)
            ->where('s.sum_num<=b.warn_num')
            ->whereNull('b.delete_at')
            ->count('s.id');
    }



    /**
     * 回收指定的店铺的虚码库存
     * @param int    $shopId 源店IP
     * @param string $productCode 商品码
     * @param int    $num 回收数量
     * @param int    $opUser 操作人
     * @return void
     * @throws DbException
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function recycleShopVirtualStock(int $shopId, string $productCode, int $num, int $opUser)
    {
        $info = $this->db()->where('shop_id', $shopId)->where('product_code', $productCode)->field('id,mer_id,sum_num')->find();
        if ($info['sum_num'] < $num) {
            throw  new Exception('店铺剩余库存数量不足,请联系经销商.', API_ERROR);
        }

        // 减少库存
        $this->db()->removeOption()->where('id', $info['id'])
            ->update([
                'in_num' => Db::raw('in_num-' . $num),
                'sum_num' => Db::raw('sum_num-' . $num),
            ]);

        // 保存日志
        ModelMerchant::OrderRecycle()->order_recycle_add(
            $info['mer_id'],
            $shopId,
            $productCode,
            $opUser,
            $num
        );


        //商户增加虚码数量
        ModelMerchant::MerchantStock()->userVirtualEdit(
            $info['mer_id'],
            1,
            $num,
            '回收店铺虚码',
            $opUser,
            $shopId
        );
    }

    /**
     * 库存调拨
     * @param     $id |id
     * @param     $op_user |操作人
     * @param     $num |变动数量
     * @param int $type | 类型： 1:增加， 2减少
     * @throws \Exception
     */
    public function shopSaveStock($id, $num, $op_user, $type = 1)
    {

        try {
            //源当前库存
            $shop = $this->db()->where(['id' => $id])->find();

            Db::startTrans();
            //源店铺
            if ($type === 1) {
                $update_num = $shop['sum_num'] + $num;
            } else {

                if ($shop['sum_num'] < $num) {
                    throw  new Exception('库存数量不足,请联系经销商.', API_ERROR);
                }
                $update_num = $shop['sum_num'] - $num;
            }
            $this->db()->where(['id' => $id])->update(['sum_num' => $update_num]);

            //日志
            ModelMerchant::OrderRecycle()->order_recycle_add(
                $shop['mer_id'],
                $shop['shop_id'],
                $shop['product_code'],
                $op_user,
                $num
            );

            Db::commit();
            return $shop['product_code'];
        } catch (\Exception $e) {
            Db::rollback();
            throw $e;
        }
    }


    /**
     * 商品库存
     * @param string $mer_id
     * @param $where
     * @param $page
     * @param $page_size
     * @return mixed
     * @throws DbException
     */
    public function shopProductStock(string $mer_id, $where, $page, $page_size)
    {
        /*$data = $this->db('product')->where($where ?? [])
            ->field('code,title,sub_title,class_id')
            ->paginate(['page' => $page, 'list_rows' => $page_size]);*/

        return $this->db('shop_stock')->where('mer_id', $mer_id)
            ->where($where)
            ->group('mer_id,product_code')
            ->field('mer_id,product_code,sum(sum_num) as sum_num,sum(out_num) as out_num')
            ->paginate(['page' => $page, 'list_rows' => $page_size]);
        // SELECT mer_id,product_code,sum(sum_num) as sum_num,sum(out_num) as out_num FROM "t_shop_stock" where mer_id='mer000007'
        // group by mer_id,product_code;


    }
}
